package com.myfoon.servlet.listener;

import java.io.Serializable;

import org.apache.commons.fileupload.ProgressListener;

import org.json.JSONException;
import org.json.JSONObject;

public class UploadProgressListener implements ProgressListener, Serializable {
    private long bytesRead;
    private long contentLength;    
    private String fileName;
    private boolean completed;
    
    public UploadProgressListener() {
    }

    public void update(long pBytesRead, long pContentLength, int pItems) {   
        this.bytesRead = pBytesRead;
        this.contentLength = pContentLength;         
    }

    public String toJSON() {
        JSONObject jObject= new JSONObject();        
        try {
            jObject.put("read", bytesRead);
            jObject.put("total", contentLength);
            int percent = (int)(bytesRead * 100 / contentLength);
            jObject.put("percent", percent);                                           
            jObject.put("fname", fileName);                                            
            
            if (percent >= 100) {
                completed = true;
            }            
        } catch (JSONException e) {
        }            
        
        return jObject.toString();
    }

    public void setBytesRead(long bytesRead) {
        this.bytesRead = bytesRead;
    }

    public long getBytesRead() {
        return bytesRead;
    }

    public void setContentLength(long contentLength) {
        this.contentLength = contentLength;
    }

    public long getContentLength() {
        return contentLength;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() {
        return fileName;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }

    public boolean isCompleted() {
        return completed;
    }
}
